package com.qf.controller;

import com.qf.mapper.TicketMapper;
import com.qf.pojo.Ticket;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.spring.boot.CuratorZkTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/ticket")
public class TicketController {

    @Autowired
    private TicketMapper ticketMapper;

    @Value("${winnum}")
    private Integer winnum;

    @Autowired
    private CuratorZkTemplate zkTemplate;

    public static final String LOCK_PREFIX = "/LOCK-";


    @GetMapping("/sell/{id}")
    public void sell(@PathVariable("id") Integer id) throws Exception {

        while (true){
            //通过分布式锁控制多进程间共享数据的操作安全
            InterProcessLock lock = zkTemplate.getSharedReentrantLock(LOCK_PREFIX+id);

            try {
                //加锁
                lock.acquire();

                Ticket ticket = ticketMapper.selectById(id);
                //查询是否有票
                if (ticket.getCount() > 0) {
                    //有票
                    System.out.println(winnum + "窗口正在卖出第" + ticket.getCount() + "张票");

                    //模拟卖票耗时
                    Thread.sleep(1000);

                    ticket.setCount(ticket.getCount() - 1);

                    //将新的票数设置到数据库
                    ticketMapper.updateById(ticket);

                    System.out.println(winnum + "窗口卖出票后，剩余票数为: " + ticket.getCount());
                } else {
                    //没票
                    break;
                }
            }finally {
                lock.release();
            }
        }

    }
}
